package handler

import (
	"sen-golang-study/go_game_study/hero_story_go_server/biz_server/service/user/user_lazy_save_service"
	"sen-golang-study/go_game_study/hero_story_go_server/biz_server/service/user/userdata"
	"sen-golang-study/go_game_study/hero_story_go_server/common/lazy_save_service"
	"sen-golang-study/go_game_study/hero_story_go_server/common/log"
	"sen-golang-study/go_game_study/hero_story_go_server/common/server_msg/proto_msg"
)

func HandleOnUserQuit(ctx CmdContext) {
	if ctx == nil {
		return
	}

	log.Info("用户离线，userId=%d", ctx.GetUserId())

	GetCmdContextGroup().UnRegister(ctx.GetId())
	GetCmdContextGroup().Broadcast(&proto_msg.UserQuitResult{
		QuitUserId: ctx.GetUserId(),
	})

	user := userdata.GetUserGroup().GetByUserId(ctx.GetUserId())

	if user == nil {
		return
	}

	userLazySaver := user_lazy_save_service.GetUserLazySaver(user)
	lazy_save_service.Cancel(userLazySaver)

	log.Info("用户离线，立即保存数据！userId=%d", ctx.GetUserId())

	userLazySaver.SaveOrUpdate()
}
